package com.hb.back.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hb.common.domain.*;
import com.hb.common.service.*;
import com.hb.common.vo.CourseInfoVo;
import com.hb.common.vo.CoursepublishVO;
import com.hb.common.vo.ResultVo;
import io.swagger.v3.oas.annotations.Operation;
import jdk.jfr.Name;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/course")
public class CourseController {

    @Autowired
    EduTeacherService eduTeacherService;
    @Autowired
    EduSubjectService subjectService;
    @Autowired
    EduCourseService eduCourseService;
    @Autowired
    EduCourseDescriptionService courseDescriptionService;
    @Autowired
    EduVideoService eduVideoService;
    @Autowired
    RedisTemplate redisTemplate;
    @Value("${ali.bucketName}")
    private String   bucketName ;     // 存储桶名称
    private String endpoint="https://zxjy-ondemand.oss-cn-hangzhou.aliyuncs.com";             //OSS的储存桶地址
    @Value("${ali.accessKeyId}")
    private String accessKeyId;      // 阿里云 OSS 访问密钥
    @Value("${ali.secretAccessKey}")
    private String secretAccessKey;
    @Name("Oss图片储存路径")
    private String ossKey;
    @PostMapping("/{type}")
    @Operation(summary = "图片上传")
    public ResultVo seaveImg(@PathVariable String type, MultipartFile file) throws IOException {
        String fileName=file.getOriginalFilename();
        String oldName=fileName.substring(fileName.lastIndexOf("."));
        SimpleDateFormat  format= new SimpleDateFormat();
        String dataPath = format.format(new Date());
        ossKey = dataPath + "/" + UUID.randomUUID().toString().replace("-", "")+oldName;
        OSS ossClient = new OSSClientBuilder().build("https://oss-cn-hangzhou.aliyuncs.com", accessKeyId, secretAccessKey);
        try {
            // 创建 PutObjectRequest 对象，指定上传的本地文件和存储在 OSS 中的路径
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, ossKey,file.getInputStream());
            // 上传图片
            ossClient.putObject(putObjectRequest);
            System.out.println(ossKey);
        } catch (Exception e) {
            System.err.println("图片上传失败：" + e.getMessage());
        } finally {
            //关闭文件输入流
            file.getInputStream().close();
            // 关闭 OSS 客户端
            ossClient.shutdown();
        }
        return ResultVo.success("文件上传成功!",endpoint+"/"+ossKey);
    }
    @PostMapping("/create")
    public ResultVo create(@RequestBody CourseInfoVo courseInfoVo){
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVo,eduCourse);
        eduCourse.setIsDeleted(0);
        boolean insert = eduCourseService.save(eduCourse);
        if(!insert) {
            //添加失败
            return ResultVo.error("添加课程信息失败",null);
        }
        //获取添加之后课程id
        String cid = eduCourse.getId();
        //2 向课程简介表添加课程简介
        //edu_course_description
        EduCourseDescription courseDescription = new EduCourseDescription();
        courseDescription.setDescription(courseInfoVo.getDescription());
        //设置描述id就是课程id
        courseDescription.setId(cid);
        courseDescriptionService.save(courseDescription);
        return ResultVo.success("添加课程信息成功",cid);
    }
    //发布课程
    @GetMapping("/fabu/{id}")
    public ResultVo getpulic(@PathVariable String id){
        try {
            EduCourse eduCourse = new EduCourse();
            eduCourse.setId(id);
            eduCourse.setStatus("Normal");
            boolean b = eduCourseService.updateById(eduCourse);
            if (b){
                EduCourse one = eduCourseService.getOne(new LambdaQueryWrapper<EduCourse>().eq(EduCourse::getId, eduCourse.getId()));
                redisTemplate.opsForList().leftPush("Key",one);
                Long size = redisTemplate.opsForList().size("Key");
                if (size>4){
                    redisTemplate.opsForList().trim("Key",0,3);
                }
            }
        }catch (Exception e) {
            return ResultVo.error("",null);
        }
        return ResultVo.success("",null);
    }

    @GetMapping("/public/{id}")
    public ResultVo getpublic(@PathVariable String id){
        CoursepublishVO coursepublishVO=new CoursepublishVO();
        try {
            EduCourse byId = eduCourseService.getById(id);
            EduSubject byId1 = subjectService.getById(byId.getSubjectId());
            EduSubject one = subjectService.getById(byId.getSubjectParentId());
            EduTeacher byId2 = eduTeacherService.getById(byId.getTeacherId());
            coursepublishVO.setTitle(byId.getTitle());
            coursepublishVO.setPrice(byId.getPrice());
            coursepublishVO.setLessonNum(byId.getLessonNum());
            coursepublishVO.setSubjectName(byId1.getTitle());
            coursepublishVO.setSubjectParentName(one.getTitle());
            coursepublishVO.setTeacherName(byId2.getName());
            coursepublishVO.setCover(byId.getCover());
        }catch (Exception e) {
            return ResultVo.error("",null);
        }
        return ResultVo.success("",coursepublishVO);
    }

    @GetMapping("/delete/{id}")
    public ResultVo getdel(@PathVariable String id){
        boolean b = eduCourseService.removeById(id);
        if (b){
            LambdaQueryWrapper<EduVideo> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(EduVideo::getCourseId,id);
            courseDescriptionService.removeById(id);
            eduVideoService.remove(queryWrapper);
            return ResultVo.success("",null);
        }
        return ResultVo.error("",null);
    }

    @GetMapping("/huixian/{id}")
    public ResultVo gethuixian(@PathVariable String id){
        EduCourse byId = eduCourseService.getById(id);
        EduCourseDescription byId1 = courseDescriptionService.getById(id);
        byId.setDescription(byId1.getDescription());
        if (byId!=null){
            return ResultVo.success("",byId);
        }
        return ResultVo.error("",null);
    }

    @PostMapping("/page")
    @Operation(summary = "课程的分页待条件查询")
    public ResultVo page(@RequestBody CourseInfoVo searchTeacherDto,
                         @RequestParam(defaultValue = "1") Integer pagenum,
                         @RequestParam(defaultValue = "3") Integer pagesize){
        if (searchTeacherDto.getPagenum()!=null&&searchTeacherDto.getPagenum()>1){
            pagenum=searchTeacherDto.getPagenum();
        }
        LambdaQueryWrapper<EduCourse> queryWrapper=new LambdaQueryWrapper<>();
        if (!ObjectUtils.isEmpty(searchTeacherDto)){
            if (!ObjectUtils.isEmpty(searchTeacherDto.getTitle())){
                queryWrapper.like(EduCourse::getTitle,searchTeacherDto.getTitle());
            }
            if (!ObjectUtils.isEmpty(searchTeacherDto.getStatus())){
                queryWrapper.eq(EduCourse::getStatus,searchTeacherDto.getStatus());
            }
            queryWrapper.orderByDesc(EduCourse::getId);
            Page<EduCourse> page = eduCourseService.page(new Page<>(pagenum, pagesize), queryWrapper);
            return ResultVo.success("",page);
        }
        return ResultVo.error("",null);
    }





    @GetMapping("/one")
    @Operation(summary = "一级分类")
    public ResultVo SubjectList(){
        LambdaQueryWrapper<EduSubject>subjectLambdaQueryWrapper=new LambdaQueryWrapper<>();
        subjectLambdaQueryWrapper.eq(EduSubject::getParentId,0);
        List<EduSubject> list = subjectService.list(subjectLambdaQueryWrapper);
        return ResultVo.success("",list);
    }

    @GetMapping("/tow/{id}")
    @Operation(summary = "二级分类")
    public ResultVo subjectPart(@PathVariable Long id){
        LambdaQueryWrapper<EduSubject>subjectLambdaQueryWrapper=new LambdaQueryWrapper<>();
        subjectLambdaQueryWrapper.eq(EduSubject::getParentId,id);
        List<EduSubject> list = subjectService.list(subjectLambdaQueryWrapper);
        return ResultVo.success("",list);
    }

    @GetMapping("/teacher")
    @Operation(summary = "添加讲师")
    public ResultVo TeacherList(){
        return ResultVo.success("",eduTeacherService.list());
    }
}
